# Lawn Signs Helper Functions

library(sandwich)
library(lmtest)

commarobust <- function(fit){
  require(sandwich)
  require(lmtest)
  coeftest(fit,vcovHC(fit, type = "HC2"))
}

getrobustses <- function(fit){
  robustfit <- commarobust(fit)
  return(robustfit[,2])
}

makerobustseslist <- function(fitlist){
  return(lapply(fitlist, FUN=getrobustses) )
}

get_condition<- function(Z, adj){
  spillovers <- adj %*% Z
  condition <- rep(NA, length(Z))
  condition[Z==1] <- "treated" 
  condition[Z==0 & spillovers>0] <- "adjacent"
  condition[Z==0 & spillovers==0] <- "control"
  return(condition)
}


get_prob_obs <- function(Z){
  prob_obs <- rep(NA, length(Z))
  prob_obs[Z=="control"] <- PA_41_df$res_prob_control[Z=="control"]
  prob_obs[Z=="treated"] <- PA_41_df$res_prob_treated[Z=="treated"]
  prob_obs[Z=="adjacent"] <- PA_41_df$res_prob_adj[Z=="adjacent"]
  return(prob_obs)
}

get_f <- function(formula_F, treat_var, weights, data){
  data$w = data[,weights]
  ftest.F <- lm(formula_F, weights=w, data=data)
  formula_R <- gsub(pattern = paste0(treat_var,  " \\+"), replacement = "", x = formula_F)
  ftest.R <- lm(formula_R, weights=w, data=data)
  ftest <- anova(ftest.R, ftest.F)
  return(ftest$F[2])
}

paratheses_appender <- function(x, digits){
  x_round <- sprintf(paste0("%.",digits,"f"), x)
  return(paste0("(", x_round, ")"))
}

lmp <- function (modelobject) {
  if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
  f <- summary(modelobject)$fstatistic
  p <- pf(f[1],f[2],f[3],lower.tail=F)
  attributes(p) <- NULL
  return(p)
}

multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  require(grid)
  
  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)
  
  numPlots = length(plots)
  
  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                     ncol = cols, nrow = ceiling(numPlots/cols))
  }
  
  if (numPlots==1) {
    print(plots[[1]])
    
  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
    
    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
      
      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}